<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多人迷宫探险</title>
    <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Roboto:wght@400;700&display=swap"
          rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Roboto', sans-serif;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
            color: #fff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            overflow-x: hidden;
        }

        .container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        header {
            text-align: center;
            padding: 20px 0;
            margin-bottom: 20px;
            width: 100%;
        }

        h1 {
            font-family: 'Press Start 2P', cursive;
            font-size: 2.5rem;
            color: #ffcc00;
            text-shadow: 3px 3px 0 #ff6b00, 5px 5px 0 rgba(0, 0, 0, 0.2);
            margin-bottom: 15px;
            letter-spacing: 2px;
        }

        .subtitle {
            font-size: 1.2rem;
            color: #ffdd99;
            max-width: 800px;
            margin: 0 auto 20px;
            line-height: 1.6;
        }

        .game-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 30px;
            width: 100%;
            margin-bottom: 30px;
        }

        .maze-section {
            flex: 1;
            min-width: 500px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .controls-section {
            width: 300px;
            background: rgba(0, 0, 0, 0.7);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .section-title {
            font-size: 1.5rem;
            color: #4dabf7;
            margin-bottom: 20px;
            text-align: center;
            font-weight: bold;
        }

        .maze-grid {
            display: grid;
            gap: 2px;
            width: 100%;
            aspect-ratio: 1/1;
            background: #444;
            border: 3px solid #ff6b00;
            border-radius: 5px;
            overflow: hidden;
            position: relative;
        }

        .cell {
            background: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background-color 0.3s;
            position: relative;
        }

        .cell.wall {
            background: #1a237e;
        }

        .cell.path {
            background: #222;
        }

        .cell.start {
            background: #4caf50;
        }

        .cell.end {
            background: #f44336;
        }

        .cell.player {
            position: relative;
            z-index: 10;
        }

        .player-marker {
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 10px;
            z-index: 20;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
            transition: transform 0.2s;
        }

        .player-marker.active {
            transform: scale(1.2);
            box-shadow: 0 0 8px white;
            z-index: 30;
        }

        .player-1 {
            background: #ffeb3b;
            color: #000;
            top: 5px;
            left: 5px;
        }

        .player-2 {
            background: #2196F3;
            color: #fff;
            top: 5px;
            right: 5px;
        }

        .player-3 {
            background: #4CAF50;
            color: #fff;
            bottom: 5px;
            left: 5px;
        }

        .player-4 {
            background: #ffffff;
            color: #000;
            bottom: 5px;
            right: 5px;
        }

        .cell.visited {
            background: rgba(76, 175, 80, 0.3);
        }

        .btn {
            display: block;
            width: 100%;
            padding: 15px;
            margin: 15px 0;
            font-size: 1.1rem;
            font-weight: bold;
            color: white;
            background: linear-gradient(to right, #ff6b00, #ffcc00);
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 5px 15px rgba(255, 107, 0, 0.4);
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(255, 107, 0, 0.6);
        }

        .btn:active {
            transform: translateY(1px);
        }

        .btn.secondary {
            background: linear-gradient(to right, #4a69bd, #6a89cc);
        }

        .stats {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
            text-align: center;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #ffcc00;
            margin: 10px 0;
        }

        .stat-label {
            font-size: 1rem;
            color: #aaa;
        }

        .instructions {
            background: rgba(0, 0, 0, 0.5);
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }

        .instructions h3 {
            color: #4dabf7;
            margin-bottom: 15px;
        }

        .instructions ul {
            padding-left: 20px;
        }

        .instructions li {
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .key-controls {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-top: 20px;
        }

        .key {
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #ffcc00;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.2s;
        }

        .key:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .key:active {
            background: rgba(255, 204, 0, 0.3);
            transform: translateY(1px);
        }

        .difficulty-controls {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
        }

        .difficulty-btn {
            padding: 10px 15px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid #4dabf7;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }

        .difficulty-btn.active {
            background: #4dabf7;
            font-weight: bold;
        }

        .player-controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .player-btn {
            width: 22%;
            padding: 8px;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            border: 2px solid #666;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
        }

        .player-btn.active {
            border-color: #ffcc00;
            background: rgba(255, 204, 0, 0.2);
            transform: translateY(-3px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }

        .player-btn .player-indicator {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-bottom: 5px;
        }

        .player-btn-1 .player-indicator {
            background: #ffeb3b;
        }

        .player-btn-2 .player-indicator {
            background: #2196F3;
        }

        .player-btn-3 .player-indicator {
            background: #4CAF50;
        }

        .player-btn-4 .player-indicator {
            background: #ffffff;
        }

        /* 移除链接下划线并设置文字颜色 */
        .player-btn a {
            text-decoration: none;
            color: white;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .player-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: #999;
        }

        @media (max-width: 900px) {
            .game-container {
                flex-direction: column;
                align-items: center;
            }

            .maze-section {
                min-width: 100%;
            }

            .controls-section {
                width: 100%;
            }

            h1 {
                font-size: 1.8rem;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>多人迷宫探险</h1>
        <p class="subtitle">控制玩家从起点到达终点！使用方向键移动当前玩家，数字键1-4切换玩家。当前玩家：<span
                id="current-player-display">1</span></p>
    </header>

    <div class="game-container">
        <div class="maze-section">
            <h2 class="section-title">迷宫区域</h2>
            <div class="maze-grid" id="maze"></div>
        </div>

        <div class="controls-section">
            <h2 class="section-title">游戏控制</h2>

            <div class="player-controls" id="player-controls">
                <!-- 玩家按钮将通过JavaScript动态生成 -->
            </div>

            <div class="stats">
                <div class="stat-label">难度</div>
                <div class="stat-value" id="difficulty-display">简单</div>
            </div>

            <div class="stats">
                <div class="stat-label">迷宫尺寸</div>
                <div class="stat-value" id="maze-size-display">15x15</div>
            </div>

            <div class="stats">
                <div class="stat-label">当前时间</div>
                <div class="stat-value" id="timer">00:00</div>
            </div>

            <div class="stats">
                <div class="stat-label">最佳时间</div>
                <div class="stat-value" id="bestTime">00:00</div>
            </div>

            <button class="btn" id="resetBtn">重置玩家位置</button>

            <div class="key-controls">
                <div class="key up" data-direction="up">W / ↑</div>
                <div class="key left" data-direction="left">A / ←</div>
                <div class="key right" data-direction="right">D / →</div>
                <div class="key down" data-direction="down">S / ↓</div>
                <div class="key" data-function="switch">1-4</div>
                <div class="key" data-function="switch">切换玩家</div>
            </div>
        </div>
    </div>

    <div class="instructions">
        <h3>游戏说明</h3>
        <ul>
            <li>点击<strong>方向键按钮</strong>或使用键盘<strong>方向键</strong>移动<strong>当前玩家</strong></li>
            <li>点击<strong>切换玩家按钮</strong>或按<strong>数字键1-4</strong>切换当前玩家</li>
            <li>从<strong style="color:#4caf50">绿色起点</strong>出发，到达<strong
                    style="color:#f44336">红色终点</strong></li>
            <li>所有玩家都需要到达终点才能获胜</li>
            <li>游戏会自动记录你的最佳完成时间</li>
            <li>按<strong>方向键</strong>移动的同时会保存当前游戏状态到数据库</li>
        </ul>
    </div>

    <!-- 响应区域 -->
    <div id="responseArea"
         style="margin: 20px auto; padding: 15px; background: rgba(0,0,0,0.5); border-radius: 10px; max-width: 600px; text-align: center;"></div>

    <!-- 表单 (隐藏但保留以维持CSRF令牌) -->
    <form id="mazeGenerate_save_Form" style="display: none;">
        <button type="submit" class="btn" style="margin-top: 10px;">保存到数据库</button>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 从Django模板获取游戏数据
        let gameData = {% if game_data %}{{ game_data | safe }}
        {% else %}
        null{% endif %};

        // 游戏配置
        const config = {
            mazeSize: 15,
            players: [],
            currentPlayerId: {{ play_id }},
            end: {x: 0, y: 0},
            timer: 0,
            timerInterval: null,
            bestTime: 0,
            mazeData: []
        };

        // DOM元素
        const mazeElement = document.getElementById('maze');
        const resetBtn = document.getElementById('resetBtn');
        const timerElement = document.getElementById('timer');
        const bestTimeElement = document.getElementById('bestTime');
        const currentPlayerDisplay = document.getElementById('current-player-display');
        const playerControls = document.getElementById('player-controls');
        const difficultyDisplay = document.getElementById('difficulty-display');
        const mazeSizeDisplay = document.getElementById('maze-size-display');
        const keyButtons = document.querySelectorAll('.key');
        const responseArea = document.getElementById('responseArea');
        const saveForm = document.getElementById('mazeGenerate_save_Form');

        // 新增：页面刷新定时器
        let refreshInterval;

        // 保存状态变量，避免频繁发送请求
        let isSaving = false;
        let lastSaveTime = 0;
        const SAVE_DEBOUNCE_TIME = 0; // 保存请求间隔时间(毫秒)

        // 初始化游戏
        function initGame() {
            if (!gameData) {
                alert('没有找到游戏数据！');
                return;
            }

            // 设置游戏配置
            config.mazeSize = gameData.maze_size;
            config.mazeData = gameData.maze_data;
            config.players = gameData.players;
            config.currentPlayerId = {{ play_id }};
            config.end = gameData.end_position;
            config.bestTime = gameData.best_time || 0;

            // 更新UI显示
            difficultyDisplay.textContent = gameData.difficulty;
            mazeSizeDisplay.textContent = `${gameData.maze_size}x${gameData.maze_size}`;
            currentPlayerDisplay.textContent = gameData.current_player;

            // 更新最佳时间显示
            updateBestTimeDisplay();

            // 创建玩家控制按钮
            createPlayerControls();

            // 渲染迷宫
            renderMaze();

            // 添加事件监听
            document.addEventListener('keydown', handleKeyPress);
            resetBtn.addEventListener('click', resetPlayers);

            // 为方向键按钮添加点击事件
            keyButtons.forEach(button => {
                if (button.dataset.direction) {
                    button.addEventListener('click', () => handleDirectionButtonClick(button.dataset.direction));
                } else if (button.dataset.function === 'switch') {
                    button.addEventListener('click', showPlayerSwitchPrompt);
                }
            });

            // 启动计时器
            startTimer();

            // 新增：启动页面刷新定时器（每秒刷新一次）
            startRefreshTimer();
        }


        // 新增：启动页面刷新定时器
        function startRefreshTimer() {
            refreshInterval = setInterval( () => {
                location.reload();

            }, 1000);
        }

        // 处理方向键按钮点击
        function handleDirectionButtonClick(direction) {
            let dx = 0, dy = 0;

            // 根据方向设置偏移量
            switch (direction) {
                case 'up':
                    dy = -1;
                    break;
                case 'right':
                    dx = 1;
                    break;
                case 'down':
                    dy = 1;
                    break;
                case 'left':
                    dx = -1;
                    break;
            }

            // 移动玩家
            movePlayer(dx, dy);

            // 添加按钮点击效果
            const button = document.querySelector(`.key[data-direction="${direction}"]`);
            if (button) {
                button.classList.add('active');
                setTimeout(() => {
                    button.classList.remove('active');
                }, 150);
            }
        }

        // 显示玩家切换提示
        function showPlayerSwitchPrompt() {
            const playerId = prompt('请输入要切换到的玩家编号 (1-4):');
            if (playerId && playerId >= 1 && playerId <= 4) {
                const id = parseInt(playerId);
                if (config.players.some(p => p.id === id)) {
                    switchPlayer(id);
                } else {
                    alert(`玩家 ${id} 不存在！`);
                }
            }
        }

        // 创建玩家控制按钮
        function createPlayerControls() {
            playerControls.innerHTML = '';

            config.players.forEach(player => {
                const playerBtn = document.createElement('div');
                playerBtn.className = `player-btn player-btn-${player.id}`;
                if (player.id === config.currentPlayerId) {
                    playerBtn.classList.add('active');
                }
                playerBtn.dataset.player = player.id;

                playerBtn.innerHTML = `
                        <div class="player-indicator"></div>
                        <div>玩家 ${player.id}</div>
                    `;

                playerBtn.addEventListener('click', () => {
                    switchPlayer(player.id);
                });

                playerControls.appendChild(playerBtn);
            });
        }

        // 切换当前玩家
        function switchPlayer(playerId) {
            config.currentPlayerId = playerId;
            currentPlayerDisplay.textContent = playerId;

            // 更新UI
            document.querySelectorAll('.player-btn').forEach(btn => {
                if (parseInt(btn.dataset.player) === playerId) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            });

            renderMaze();
        }

        // 渲染迷宫到DOM
        function renderMaze() {
            mazeElement.innerHTML = '';
            mazeElement.style.gridTemplateColumns = `repeat(${config.mazeSize}, 1fr)`;

            for (let y = 0; y < config.mazeSize; y++) {
                for (let x = 0; x < config.mazeSize; x++) {
                    const cell = document.createElement('div');
                    cell.classList.add('cell');

                    // 添加对应的类
                    const cellType = config.mazeData[y][x];
                    if (cellType === 1) {
                        cell.classList.add('wall');
                    } else {
                        cell.classList.add('path');
                    }

                    // 检查是否是起点
                    gameData.start_positions.forEach(pos => {
                        if (pos[0] === x && pos[1] === y) {
                            cell.classList.add('start');
                        }
                    });

                    // 检查是否是终点
                    if (config.end && config.end[0] === x && config.end[1] === y) {
                        cell.classList.add('end');
                    }

                    // 检查此单元格是否有玩家
                    const playersHere = config.players.filter(p => p.x === x && p.y === y);

                    // 如果有玩家，添加玩家标记
                    playersHere.forEach(player => {
                        const playerMarker = document.createElement('div');
                        playerMarker.classList.add('player-marker', `player-${player.id}`);
                        playerMarker.textContent = player.id;
                        if (player.id === config.currentPlayerId) {
                            playerMarker.classList.add('active');
                        }
                        cell.appendChild(playerMarker);
                        cell.classList.add('player');
                    });

                    mazeElement.appendChild(cell);
                }
            }
        }

        // 处理键盘事件
        function handleKeyPress(e) {
            // 数字键1-4切换玩家
            if (e.key >= '1' && e.key <= '4') {
                const playerId = parseInt(e.key);
                if (config.players.some(p => p.id === playerId)) {
                    switchPlayer(playerId);
                }
                return;
            }

            let dx = 0, dy = 0;

            // 方向键和WASD控制
            if (e.key === 'ArrowUp' || e.key === 'w' || e.key === 'W') dy = -1;
            if (e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') dx = 1;
            if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') dy = 1;
            if (e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') dx = -1;

            // 如果有移动方向
            if (dx !== 0 || dy !== 0) {
                movePlayer(dx, dy);

                // 保存游戏状态到数据库
                saveGameState();
            }
        }

        // 移动玩家
        function movePlayer(dx, dy) {
            const player = config.players.find(p => p.id === config.currentPlayerId);
            if (!player || player.completed) return;

            const newX = player.x + dx;
            const newY = player.y + dy;

            // 检查是否可以移动（在边界内且不是墙）
            if (newX >= 0 && newX < config.mazeSize &&
                newY >= 0 && newY < config.mazeSize &&
                config.mazeData[newY][newX] !== 1) {

                // 更新玩家位置
                player.x = newX;
                player.y = newY;

                // 重新渲染迷宫
                renderMaze();

                // 检查是否到达终点
                if (config.end && newX === config.end[0] && newY === config.end[1]) {
                    player.completed = true;

                    // 检查是否所有玩家都已完成
                    if (config.players.every(p => p.completed)) {
                        finishGame();
                    } else {
                        // 提示当前玩家已完成
                        const playerBtn = document.querySelector(`.player-btn[data-player="${player.id}"]`);
                        if (playerBtn) {
                            playerBtn.style.borderColor = '#4CAF50';
                            playerBtn.style.background = 'rgba(76, 175, 80, 0.3)';
                        }
                    }
                }
            }
        }

        // 保存游戏状态到数据库
        async function saveGameState() {
            // 防止频繁请求
            const currentTime = Date.now();
            if (isSaving || (currentTime - lastSaveTime) < SAVE_DEBOUNCE_TIME) {
                return;
            }

            isSaving = true;
            lastSaveTime = currentTime;

            // 显示保存中消息
            responseArea.innerHTML = `<p>正在保存游戏状态...</p>`;

            try {
                // 创建FormData对象收集表单数据
                const formData = new FormData(saveForm);

                // 添加游戏数据
                if (gameData) {
                    formData.append('game_data', JSON.stringify(gameData));
                }

                // 添加当前游戏状态
                formData.append('size', config.mazeSize);
                formData.append('current_player', config.currentPlayerId);
                formData.append('game_time', config.timer);
                formData.append('best_time', config.bestTime);

                // 添加玩家位置
                config.players.forEach(player => {
                    formData.append(`player_${player.id}_x`, player.x);
                    formData.append(`player_${player.id}_y`, player.y);
                    formData.append(`player_${player.id}_completed`, player.completed ? '1' : '0');
                });

                // 发送POST请求到Django视图
                const response = await fetch("{% url 'Labyrinth_app:labyrinth_sql_save_common' play_id=play_id %}", {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}'
                    }
                });

                // 解析响应
                const data = await response.json();

                if (data.status === 'success') {
                    responseArea.innerHTML = `
                            <p style="color: #4caf50; font-weight: bold;">✅ 游戏状态已保存！</p>
                            <p>保存时间: ${new Date().toLocaleTimeString()}</p>
                        `;

                    // 3秒后清除保存消息
                    setTimeout(() => {
                        responseArea.innerHTML = '';
                    }, 3000);
                } else {
                    responseArea.innerHTML = `<p style="color: #f44336; font-weight: bold;">❌ 保存失败: ${data.message || '未知错误'}</p>`;
                }
            } catch (error) {
                responseArea.innerHTML = `<p style="color: #f44336; font-weight: bold;">❌ 网络错误: ${error.message}</p>`;
                console.error('异步请求错误:', error);
            } finally {
                isSaving = false;
            }
        }

        // 重置玩家位置
        function resetPlayers() {
            // 重置玩家到起点
            config.players.forEach(player => {
                const startPos = gameData.start_positions[0] || [1, 1];
                player.x = startPos[0];
                player.y = startPos[1];
                player.completed = false;
            });

            // 重置玩家按钮样式
            document.querySelectorAll('.player-btn').forEach(btn => {
                btn.style.borderColor = '';
                btn.style.background = '';
            });

            renderMaze();

            // 重置计时器
            clearInterval(config.timerInterval);
            config.timer = 0;
            updateTimerDisplay();
            config.timerInterval = null;

            // 重新启动计时器
            startTimer();
        }

        // 开始计时
        function startTimer() {
            if (config.timerInterval) return;

            config.timerInterval = setInterval(() => {
                config.timer++;
                updateTimerDisplay();
            }, 1000);
        }

        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(config.timer / 60).toString().padStart(2, '0');
            const seconds = (config.timer % 60).toString().padStart(2, '0');
            timerElement.textContent = `${minutes}:${seconds}`;
        }

        // 更新最佳时间显示
        function updateBestTimeDisplay() {
            if (config.bestTime > 0) {
                const minutes = Math.floor(config.bestTime / 60).toString().padStart(2, '0');
                const seconds = (config.bestTime % 60).toString().padStart(2, '0');
                bestTimeElement.textContent = `${minutes}:${seconds}`;
            } else {
                bestTimeElement.textContent = "00:00";
            }
        }

        // 完成游戏
        function finishGame() {
            clearInterval(config.timerInterval);

            // 更新最佳时间
            if (config.bestTime === 0 || config.timer < config.bestTime) {
                config.bestTime = config.timer;
                updateBestTimeDisplay();
                alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！新记录！`);
            } else {
                alert(`恭喜！所有玩家以${timerElement.textContent}的成绩完成了迷宫！`);
            }
        }

        // 游戏初始化
        initGame();
    });
</script>
</body>
</html>